package com.my.exception;

import cn.hutool.core.bean.BeanUtil;
import com.my.core.api.R;
import com.my.core.api.ResultCode;
import com.my.event.publisher.ErrorLogPublisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.WebRequest;

import java.util.Map;

/**
 * @author timo 2021/2/25
 */
public class CustomErrorAttributes extends DefaultErrorAttributes {
    private static final Logger log = LoggerFactory.getLogger(CustomErrorAttributes.class);

    public CustomErrorAttributes() {
    }

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        String requestUri = (String)this.getAttr(webRequest, "javax.servlet.error.request_uri");
        Integer status = (Integer)this.getAttr(webRequest, "javax.servlet.error.status_code");
        Throwable error = this.getError(webRequest);
        R result;
        if (error == null) {
            log.error("URL:{} error status:{}", requestUri, status);
            if(status==404){
                result = R.fail(ResultCode.FAILURE, "[HttpStatus]:" + status);
            }else{
                result = R.fail(ResultCode.FAILURE, "系统未知异常[HttpStatus]:" + status);
            }
        } else {
            log.error(String.format("URL:%s error status:%d", requestUri, status), error);
            result = R.fail(status, error.getMessage());
        }
        ErrorLogPublisher.publishEvent(error, requestUri);
        return  BeanUtil.beanToMap(result);
    }

    @Nullable
    private <T> T getAttr(WebRequest webRequest, String name) {
        return (T) webRequest.getAttribute(name, 0);
    }
}
